import os
import base64
import requests
import json

# 定义上传接口的 URL
upload_url = "http://106.54.192.233:8080/uploadAsset"

# 定义请求头
headers = {
    "Content-Type": "application/json"
}

# 定义 images 文件夹路径
images_folder = "images"

def upload(file_name_without_extension, encoded_file, file, overwrite=False):
    # 构建请求体
    data = {
        "name": file_name_without_extension,
        "type": "image/png",                 # 文件类型为 PNG
        "asset": f"data:image/png;base64,{encoded_file}",  # 带格式的 Base64 编码
        "overwrite": overwrite              # 是否覆盖
    }
    
    # 发送 POST 请求
    response = requests.post(upload_url, json=data, headers=headers)

    # 检查响应状态码
    if response.status_code == 200:
        response_data = response.json()
        print(f"文件 {file} 上传成功: {response_data}")
    else:
        print(f"文件 {file} 上传失败，状态码: {response.status_code}, 响应: {response.text}")

# 定义上传文件的函数
def upload_png_files(folder_path, overwrite=False):
    # 遍历文件夹中的所有 PNG 文件
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith('.png'):
                file_path = os.path.join(root, file)
                try:
                    # 读取文件内容并进行 Base64 编码
                    with open(file_path, "rb") as f:
                        encoded_file = base64.b64encode(f.read()).decode('utf-8')

                    file_name = os.path.basename(file_path)  # 使用文件名作为 name
                    file_name_without_extension = os.path.splitext(file_name)[0]  # 去除文件扩展名

                    # print(file_name_without_extension)
                    
                    upload(file_name_without_extension, encoded_file, file, overwrite)
                    

                    if file_name_without_extension.startswith('数字'):
                        alternative_name = file_name_without_extension.replace('数字', '')
                        upload(alternative_name, encoded_file, file, overwrite)

                    if file_name_without_extension.startswith('符号'):
                        alternative_name = file_name_without_extension.replace('符号', '')
                        upload(alternative_name, encoded_file, file, overwrite)

                    if file_name_without_extension in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
                        alternative_name = '数字' + file_name_without_extension
                        upload(alternative_name, encoded_file, file, overwrite)

                except Exception as e:
                    print(f"文件 {file} 上传时发生错误: {e}")

# 调用函数上传 PNG 文件
upload_png_files(images_folder, overwrite=True)
